package com.ruoyi.mdm.utils;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.SsoConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mdm.domain.*;
import com.ruoyi.mdm.service.IMonitorEmailConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.util.*;

@Component
@Slf4j
public class EmailUtils {

    @Autowired
    private IMonitorEmailConfigService monitorEmailConfigService;


    public static void main(String[] args) {
        String to = "soky6@163.com";
        String cc = "";
        String subject = "【资生堂】_MDM PLUS 小样计算异常！";
        Map<String, String> attachments = new HashMap<>();
//        attachments.put("工单问题解决模板.docx", "C:\\Users\\15004\\Desktop\\资生堂-监控\\模板\\工单问题解决模板.docx");
        String body = "Dears,<br/>\n" +
                "今天小样价格计算失败，请及时进行检查。 <br/>\n\n" +
                "问题描述：【问题描述字段内容】<br/>\n" +
                "Regards,<br/>\n" +
                "L1运维组<br/>";
    }




    public boolean sendApproveEmail(String[] sendTo, String[] sendCc, String subject, Map<String, String> attachments, String body) {
        try {
            //查询读取邮箱
            List<SkuEmailConfig> skuEmailConfigs = monitorEmailConfigService.selectMonitorEmailConfigListByEmailType("03");
            SkuEmailConfig skuEmailConfig = skuEmailConfigs.get(0);
            ReqEmailData reqEmailData = new ReqEmailData();
            ReqEmailMessage reqEmailMessage = new ReqEmailMessage();
            // 接收人
            List<ReqToRecipient> reqToRecipients = new ArrayList<>();
            for (String address : sendTo) {
                ReqToRecipient reqToRecipient = new ReqToRecipient();
                ReqEmailAddress reqEmailAddress = new ReqEmailAddress();
                reqEmailAddress.setAddress(address);
                reqToRecipient.setEmailAddress(reqEmailAddress);
                reqToRecipients.add(reqToRecipient);
            }
            reqEmailMessage.setToRecipients(reqToRecipients);
            // 抄送人
            if (ObjectUtils.isNotEmpty(sendCc)) {
                List<ReqCcRecipient> reqCcRecipients = new ArrayList<>();
                for (String address : sendCc) {
                    ReqCcRecipient reqCcRecipient = new ReqCcRecipient();
                    ReqEmailAddress reqEmailAddress = new ReqEmailAddress();
                    reqEmailAddress.setAddress(address);
                    reqCcRecipient.setEmailAddress(reqEmailAddress);
                    reqCcRecipients.add(reqCcRecipient);
                }
                reqEmailMessage.setCcRecipients(reqCcRecipients);
            }
            //主题
            reqEmailMessage.setSubject(subject);
            //附件
            List<ReqAttachment> reqAttachments = new ArrayList<>();
            for (Map.Entry<String, String> entry : attachments.entrySet()) {
                String fileName = entry.getKey();
                String fileUrl = entry.getValue();
                ReqAttachment reqAttachment = new ReqAttachment();
                reqAttachment.setOdataType("#microsoft.graph.fileAttachment");
                reqAttachment.setName(fileName);
                reqAttachment.setContentType("text/plain");
                File file = new File(fileUrl);
                byte[] data = new byte[(int) file.length()];

                try (FileInputStream fis = new FileInputStream(file)) {
                    fis.read(data);
                }
                reqAttachment.setContentBytes(Base64.getEncoder().encodeToString(data));
                reqAttachments.add(reqAttachment);
            }
            reqEmailMessage.setAttachments(reqAttachments);
            //正文
            ReqEmailBody reqEmailBody = new ReqEmailBody();
            reqEmailBody.setContentType("HTML");
            reqEmailBody.setContent(body);
            reqEmailMessage.setBody(reqEmailBody);
            reqEmailData.setMessage(reqEmailMessage);
            //是否保存到发送邮件列表
            reqEmailData.setSaveToSentItems("false");
            sendMail(skuEmailConfig, JSONObject.toJSONString(reqEmailData));
            System.out.println("邮件发送成功！");
            return true;
        } catch (Exception e) {
            System.out.println("邮件发送失败：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public boolean sendSkuEmail(String[] sendTo, String[] sendCc, String subject, Map<String, String> attachments, String body) {
        try {
            //查询读取邮箱
            List<SkuEmailConfig> skuEmailConfigs = monitorEmailConfigService.selectMonitorEmailConfigListByEmailType("04");
            SkuEmailConfig skuEmailConfig = skuEmailConfigs.get(0);
            ReqEmailData reqEmailData = new ReqEmailData();
            ReqEmailMessage reqEmailMessage = new ReqEmailMessage();
            // 接收人
            List<ReqToRecipient> reqToRecipients = new ArrayList<>();
            for (String address : sendTo) {
                ReqToRecipient reqToRecipient = new ReqToRecipient();
                ReqEmailAddress reqEmailAddress = new ReqEmailAddress();
                reqEmailAddress.setAddress(address);
                reqToRecipient.setEmailAddress(reqEmailAddress);
                reqToRecipients.add(reqToRecipient);
            }
            reqEmailMessage.setToRecipients(reqToRecipients);
            // 抄送人
            if (ObjectUtils.isNotEmpty(sendCc)) {
                List<ReqCcRecipient> reqCcRecipients = new ArrayList<>();
                for (String address : sendCc) {
                    ReqCcRecipient reqCcRecipient = new ReqCcRecipient();
                    ReqEmailAddress reqEmailAddress = new ReqEmailAddress();
                    reqEmailAddress.setAddress(address);
                    reqCcRecipient.setEmailAddress(reqEmailAddress);
                    reqCcRecipients.add(reqCcRecipient);
                }
                reqEmailMessage.setCcRecipients(reqCcRecipients);
            }
            //主题
            reqEmailMessage.setSubject(subject);
            //附件
            List<ReqAttachment> reqAttachments = new ArrayList<>();
            for (Map.Entry<String, String> entry : attachments.entrySet()) {
                String fileName = entry.getKey();
                String fileUrl = entry.getValue();
                ReqAttachment reqAttachment = new ReqAttachment();
                reqAttachment.setOdataType("#microsoft.graph.fileAttachment");
                reqAttachment.setName(fileName);
                reqAttachment.setContentType("text/plain");
                File file = new File(fileUrl);
                byte[] data = new byte[(int) file.length()];

                try (FileInputStream fis = new FileInputStream(file)) {
                    fis.read(data);
                }
                reqAttachment.setContentBytes(Base64.getEncoder().encodeToString(data));
                reqAttachments.add(reqAttachment);
            }
            reqEmailMessage.setAttachments(reqAttachments);
            //正文
            ReqEmailBody reqEmailBody = new ReqEmailBody();
            reqEmailBody.setContentType("HTML");
            reqEmailBody.setContent(body);
            reqEmailMessage.setBody(reqEmailBody);
            reqEmailData.setMessage(reqEmailMessage);
            //是否保存到发送邮件列表
            reqEmailData.setSaveToSentItems("false");
            sendMail(skuEmailConfig, JSONObject.toJSONString(reqEmailData));
            System.out.println("邮件发送成功！");
            return true;
        } catch (Exception e) {
            System.out.println("邮件发送失败：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    public void sendMail(SkuEmailConfig skuEmailConfig, String reqData) throws Exception {
        String token = this.getToken(skuEmailConfig);
        String sendUrl = SsoConfig.getUserInfoRequestUrl() + "/sendMail";
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.add("Content-Type", "application/json");
        headers.add("Authorization", "Bearer "+token);
        HttpEntity<String> reqEntity = new HttpEntity<>(reqData, headers);
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(sendUrl, reqEntity, String.class);
//        log.debug("postForEntity={}",postForEntity.toString());
        if (null == postForEntity ||(
                postForEntity.getStatusCode() !=  HttpStatus.OK &&
                postForEntity.getStatusCode() !=  HttpStatus.CREATED &&
                postForEntity.getStatusCode() !=  HttpStatus.ACCEPTED &&
                postForEntity.getStatusCode() !=  HttpStatus.NON_AUTHORITATIVE_INFORMATION &&
                postForEntity.getStatusCode() !=  HttpStatus.NO_CONTENT &&
                postForEntity.getStatusCode() !=  HttpStatus.RESET_CONTENT &&
                postForEntity.getStatusCode() !=  HttpStatus.PARTIAL_CONTENT
                ))
        {
            Thread.sleep(30*1000);
            log.error("send email sencond time");
            postForEntity = restTemplate.postForEntity(sendUrl, reqEntity, String.class);
        }
        if (null == postForEntity ||(
                postForEntity.getStatusCode() !=  HttpStatus.OK &&
                        postForEntity.getStatusCode() !=  HttpStatus.CREATED &&
                        postForEntity.getStatusCode() !=  HttpStatus.ACCEPTED &&
                        postForEntity.getStatusCode() !=  HttpStatus.NON_AUTHORITATIVE_INFORMATION &&
                        postForEntity.getStatusCode() !=  HttpStatus.NO_CONTENT &&
                        postForEntity.getStatusCode() !=  HttpStatus.RESET_CONTENT &&
                        postForEntity.getStatusCode() !=  HttpStatus.PARTIAL_CONTENT
        ))
        {
            Thread.sleep(30*1000);
            log.error("send email third time");
            postForEntity = restTemplate.postForEntity(sendUrl, reqEntity, String.class);
        }

//        log.info("============邮件发送ResponseStatusCode ============： " + postForEntity.getStatusCode());
//        System.out.println("============邮件发送结果 ============： " + postForEntity.getBody());
    }

    public String getToken(SkuEmailConfig skuEmailConfig) throws Exception {
        String token = "";
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        String tokenRequestUrl = SsoConfig.getTokenRequestUrl();
        tokenRequestUrl = String.format(tokenRequestUrl, skuEmailConfig.getTenantId());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置urlencoded数据
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", skuEmailConfig.getClientId());
        map.add("client_secret", skuEmailConfig.getClientSecret());
        map.add("grant_type", "password");
        map.add("username", skuEmailConfig.getUserName());
        map.add("password", skuEmailConfig.getPasswd());
        map.add("scope", skuEmailConfig.getScope());
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(tokenRequestUrl, httpEntity, String.class);
        String body = postForEntity.getBody();
//        log.info("=============获取token接口返回数据============："+body);
        if (StringUtils.isNotEmpty(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (!ObjectUtils.isEmpty(jsonObject)) {
                Object accessToken = jsonObject.get("access_token");
                if (!ObjectUtils.isEmpty(accessToken)) {
                    token = String.valueOf(accessToken);
//                    log.info("=============token值============："+token);
                }
                Object expiresIn = jsonObject.get("expires_in");
            }
        }
//        log.info("=============End============");
        return token;
    }

}
